﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

public partial class UserControl_ControlDieuChinhTonKho : System.Web.UI.UserControl
{
    

    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Page.Form.DefaultButton = btnDefault.ClientID;

            if (ViewState["flag"] == null)
            {
                //ViewState["flag"] = false;
                ClearAdd();
            }
            txtDate.Text = Session["workingday"].ToString(); 
            BindGridSearch(Session["sitecode"].ToString());
        }
        
    }
    void ClearAdd()
    {
        txtSoChungTu.Text = "New";
        txtDate.Text = Session["workingday"].ToString();
        if (Session["KhoHangTemp"] != null)
        {
            Session["KhoHangTemp"] = null;
            
        }
        UpdateGridProduct();

        ViewState["flag"] = true;
        TabContainer1.ActiveTabIndex = 0;

        lblMsg.Text = "";
        lblMsg.Visible = true;
        btnSave.Text = "Lưu";
        btnDelete.Visible = false;
    }
    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        ClearAdd();
    }
    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
    }
    protected void grvProduct_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();
            Label lblSL = (Label)grvProduct.Rows[e.RowIndex].FindControl("lblSL");
            TextBox txtSLTThem = (TextBox)grvProduct.Rows[e.RowIndex].FindControl("txtSLTThem");

            if (txtSLTThem.Text == "")
            {
                txtSLTThem.Text = "0";
            }
            Double soluongton= Double.Parse(lblSL.Text);
            Double soluongTangThem = 0;
            try
            {
                soluongTangThem = Double.Parse(txtSLTThem.Text);
                lblMsg.Text = "";
                lblMsg.Visible = false;
            }
            catch {
                lblMsg.Text = "Kiểu số lượng nhập vào là số";
                lblMsg.Visible = true;
                txtSLTThem.Focus();
                return; 
            }

            DataTable table = new DataTable();
            table = (DataTable)Session["KhoHangTemp"];

            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == keys)
                {
                    if ((soluongton + soluongTangThem) < 0)
                    {
                        lblMsg.Text = "Tồn sau điều chỉnh không được nhỏ hơn 0";
                        lblMsg.Visible = true;
                        return;
                    }
                    dr[4] = soluongton + soluongTangThem ;
                    dr[3] = soluongTangThem;
                    table.AcceptChanges();
                    Session["KhoHangTemp"] = table;

                    grvProduct.EditIndex = -1;
                    grvProduct.DataSource = Session["KhoHangTemp"];
                    grvProduct.DataBind();

                    Session["EditIndex"] = null;
                }
            }

        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   
    }
    protected void grvProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();
        DataTable table = new DataTable();
        table = (DataTable)Session["KhoHangTemp"];

        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            if (dr[0].ToString() == keys)
            {
                table.Rows[i].Delete();
                table.AcceptChanges();
                Session["KhoHangTemp"] = table;
                grvProduct.EditIndex = -1;
                grvProduct.DataSource = Session["KhoHangTemp"];
                grvProduct.DataBind();

                Session["EditIndex"] = null;
                //return;
                break;
            }
            i++;
        }
    }
    protected void grvProduct_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grvProduct.EditIndex = -1;
        grvProduct.DataSource = Session["KhoHangTemp"]; 
        grvProduct.DataBind();

        Session["EditIndex"] = null;
    }
    protected void grvProduct_RowEditing(object sender, GridViewEditEventArgs e)
    {
        Session["EditIndex"] = e.NewEditIndex;
        grvProduct.EditIndex = e.NewEditIndex;
        grvProduct.DataSource = Session["KhoHangTemp"]; //Edit 08/06/2012
        grvProduct.DataBind();
        
    }
    void UpdateGridProduct()
    {
        dt=new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getDetailProductQuanlity", CommandType.StoredProcedure,
                new SqlParameter("@Sitecode", Session["sitecode"].ToString()));
            if (db.Rows.Count > 0)
            {
                grvProduct.DataSource = db;
                grvProduct.DataBind();

                Session["KhoHangTemp"] = db;
            }
        }
        catch(Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvProduct_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvProduct.PageIndex = e.NewPageIndex;
        grvProduct.DataSource = Session["KhoHangTemp"];
        grvProduct.DataBind();
    }
    protected void grvSearch_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {

                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblSoChung = (Label)grv.FindControl("lblSoChungTu");
                Label lblNgayChungTu = (Label)grv.FindControl("lblNgayChungTu");

                DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getDetailNVDieuChinhTonKhoExists", CommandType.StoredProcedure,
                    new SqlParameter("@docno", lblSoChung.Text));

                txtSoChungTu.Text = lblSoChung.Text;
                txtDate.Text = lblNgayChungTu.Text;

                Session["KhoHangTemp"] = db;

                grvProduct.DataSource = db;
                grvProduct.DataBind();

                //Edit
                btnSave.Text = "Cập nhật";
                btnDelete.Visible = true;
                //End Edit

                ViewState["flag"] = false;
                TabContainer1.ActiveTabIndex = 0;
            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        // Edit thêm ViewStat page Index
        ViewState["PageIndex"] = e.NewPageIndex;
        grvSearch.PageIndex = e.NewPageIndex;
        BindGridSearch(Session["sitecode"].ToString());
    }
    void BindGridSearch(string sitecode)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getTranTrnNoList]", CommandType.StoredProcedure,
                new SqlParameter("@Type","A"),
                new SqlParameter("@siteCode", sitecode));
            grvSearch.DataSource = db;
            grvSearch.DataBind();
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    public int CompareDate(string sdate1,string sdate2)
    {
        DateTime date1 = new DateTime(int.Parse(sdate1.Substring(6, 4)), int.Parse(sdate1.Substring(3, 2)), int.Parse(sdate1.Substring(0, 2)));
        DateTime date2 = new DateTime(int.Parse(sdate2.Substring(6, 4)), int.Parse(sdate2.Substring(3, 2)), int.Parse(sdate2.Substring(0, 2)));
        int result = DateTime.Compare(date1, date2);
        return result;

        //if (result < 0)
        //    relationship = "sdate1 is earlier than";
        //else if (result == 0)
        //    relationship = "is the same time as";
        //else
        //    relationship = "sdate 1 is later than";

    }
    protected void ImgBtnRequest_Click(object sender, ImageClickEventArgs e)
    {
        BindGridSearch(Session["sitecode"].ToString());
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (grvProduct.Rows.Count > 0)
        {
            int checkkhoaso = CompareDate(txtDate.Text, Session["workingday"].ToString());
            if (checkkhoaso < 0)
            {
                //ShowMessageBox("Ngày bạn chọn nhỏ hơn ngày đã khóa sổ trong hệ thống,ngày khóa sổ của bạn là " + Session["workingday"].ToString());
                lblMsg.Text = "Ngày bạn chọn nhỏ hơn ngày đã khóa sổ trong hệ thống,ngày khóa sổ của bạn là " + Session["workingday"].ToString();
                lblMsg.Visible = true;
                txtDate.Focus();
            }
            else
            {
                dt = new ClassExecute.ClassExecute();
                try
                {
                    string docno = "";
                    if ((bool)ViewState["flag"])
                    {
                        docno = dt.GetDataDepend(str, "[k_getDocNoModifyInventory]", CommandType.StoredProcedure, ref error,
                            new SqlParameter("@sitecode", Session["sitecode"].ToString()));
                        ViewState["flag"] = true;
                    }
                    else
                    {
                        docno = txtSoChungTu.Text;
                    }
                    
                    //foreach (GridViewRow grv in grvProduct.Rows)
                    //{
                    //    Label lblMaHang = (Label)grv.FindControl("lblMaHang");

                    //    Label lblSLTThem = (Label)grv.FindControl("lblSLTThem");

                    //    float fSoLuongTangThem = 0;
                    //    fSoLuongTangThem = float.Parse(lblSLTThem.Text);
                    //    if (fSoLuongTangThem != 0)
                    //    {
                    //        bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_insertDieuChinhTonKho", ref error,
                    //            new SqlParameter("@itemkey", lblMaHang.Text),
                    //            new SqlParameter("@docno", docno),
                    //            new SqlParameter("@Type", "A"),
                    //            new SqlParameter("@docdate", txtDate.Text),
                    //            new SqlParameter("@stockqty", fSoLuongTangThem),
                    //            new SqlParameter("@sitecode", Session["sitecode"].ToString()),
                    //            new SqlParameter("@i", i));
                    //        i++;
                    //    }
                    //}

                    //edit lai goi trong 
                    
                    //foreach (DataRow dr in ((DataTable)Session["KhoHangTemp"]).Rows)
                    DataTable dtList = ((DataTable)Session["KhoHangTemp"]);
                    for (int i = 0; i < dtList.Rows.Count; i++ )
                    {
                        //Label lblMaHang = (Label)grv.FindControl("lblMaHang");
                        //Label lblSLTThem = (Label)grv.FindControl("lblSLTThem");

                        float fSoLuongTangThem = 0;
                        fSoLuongTangThem = float.Parse(dtList.Rows[i]["Tăng thêm"].ToString());
                        if (fSoLuongTangThem != 0)
                        {
                            bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_insertDieuChinhTonKho", ref error,
                                new SqlParameter("@itemkey", dtList.Rows[i]["Mã hàng"].ToString()),
                                new SqlParameter("@docno", docno),
                                new SqlParameter("@Type", "A"),
                                new SqlParameter("@docdate", txtDate.Text),
                                new SqlParameter("@stockqty", fSoLuongTangThem),
                                new SqlParameter("@sitecode", Session["sitecode"].ToString()),
                                new SqlParameter("@i", i));
                            
                        }
                    }

                    if (Session["KhoHangTemp"] != null)
                    {
                        Session["KhoHangTemp"] = null;

                    }

                    grvProduct.DataSource = null;
                    grvProduct.DataBind();

                    //txtSoChungTu.Text = "";
                    //ShowMessageBox("Lưu thông tin thành công");

                    ClearAdd();
                    lblMsg.Text = "Lưu thông tin thành công";
                    lblMsg.Visible = true;
                }
                catch (Exception ex)
                {
                    //ShowMessageBox("Hệ thống đang bảo trì");
                    lblMsg.Text = "Hệ thống đang bảo trì";
                    lblMsg.Visible = true;

                    string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
                }
            }
        }
        else
        {
            //ShowMessageBox("Nghiệp vụ chưa được khởi tạo");
            lblMsg.Text = "Nghiệp vụ chưa được khởi tạo";
            lblMsg.Visible = true;
        }
    }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        if ((txtSoChungTu.Text != "New") || (txtSoChungTu.Text == ""))
        {
            dt = new ClassExecute.ClassExecute();
            try
            {
                bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "[ls_delTranTrn]", ref error,
                     new SqlParameter("@DocNo", txtSoChungTu.Text));
                if (kq)
                {
                    if (ViewState["flag"] != null)
                    {
                        ViewState["flag"] = false; ;
                    }
                    if (Session["KhoHangTemp"] != null)
                    {
                        Session["KhoHangTemp"] = null;
                    }
                    grvProduct.DataSource = null;
                    grvProduct.DataBind();

                    BindGridSearch(Session["sitecode"].ToString());

                    txtSoChungTu.Text = "";
                    txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");

                    //ShowMessageBox("Hoàn thành xóa nghiệp vụ điều chỉnh tồn kho");
                    ClearAdd();
                    lblMsg.Text = "Hoàn thành xóa nghiệp vụ điều chỉnh tồn kho";
                    lblMsg.Visible = true;
                }
            }
            catch
            {

            }
        }
        else
        {
            //ShowMessageBox("Nghiệp vụ chưa được khởi tạo");
            lblMsg.Text = "Nghiệp vụ chưa được khởi tạo";
            lblMsg.Visible = true;
        }
    }
    protected void btnDefault_Click(object sender, EventArgs e)
    {
        if (Session["EditIndex"] != null)
        {
            try
            {
                GridViewUpdateEventArgs ed = new GridViewUpdateEventArgs(int.Parse(Session["EditIndex"].ToString()));
                grvProduct_RowUpdating(sender, ed);
                //Session["EditIndex"] = null;
            }
            catch { return; }
        }
    }
}